package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2024/6/29 9:48
 * @Version 1.0
 */
@RestController
@RequestMapping("wx/auth")
public class WxAuthController {

//    @Autowired
//    WxAuthService wxAuthService;

    @Autowired
    SecurityManager securityManager;

//    @Autowired
//    GlobalSessionHolder sessionHolder;

    //发送的是json字符串，接收json字符串
    @PostMapping("login")
    public Object login(@RequestBody Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        //校验之类的
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            return ResponseUtil.fail(404, "用户名密码不正确");
//            throw new RuntimeException(e);
        }

//        MarketUser user = wxAuthService.login(username, password);
//        if(user == null){
//            //用户名密码错误
//            return ResponseUtil.fail(404, "用户名密码不正确");
//        }
        Session session = subject.getSession();
        MarketUser user = (MarketUser) subject.getPrincipal();

        session.setAttribute("user", user);
        Map<String,Object> data = new HashMap<>();
        Map<String,Object> userInfo = new HashMap<>();
        userInfo.put("nickName", user.getNickname());
        userInfo.put("avatarUrl", user.getAvatar());
        //token可以用session的编号，但是小程序不会携带cookie，所以session暂时用不了
        data.put("token", session.getId());
        data.put("userInfo", userInfo);
        return ResponseUtil.ok(data);
    }

    @PostMapping("logout")
    public Object logout(){
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.stop();
        return ResponseUtil.ok();
    }
}
